/**
 * @file request
 * @author lishaohai
 */
import axios from 'axios';
// import {Message} from 'element-ui';
import store from '@/store';
// create an axios instance
const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_URL, // url = base url + request url
    // `withCredentials` 表示跨域请求时是否需要使用凭证
    withCredentials: false, // 默认的
    // withCredentials: true, // send cookies when cross-domain requests
    timeout: 1000 * 60 // request timeout
});

// 请求拦截  设置统一header
service.interceptors.request.use(
    config => {
        const userStore = store.state.user;
        const userToken = userStore.userToken;
        if (userToken) {
            config.headers['Authorization'] = userToken;
        }
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

// 响应拦截  401 token过期处理
service.interceptors.response.use(
    response => {
        return response;
    },
    error => {
        // 错误提醒
        // axios在catch中获取响应状态码: https://blog.csdn.net/bianliuzhu/article/details/88170549
        const {status, config} = error.response || {};
        switch (status) {
            case 500:
                window.$message && window.$message({type: 'error', message: '服务器出错啦！'});
                // 不是获取权限菜单
                if (config.url === '/api/menus/') {
                    store.dispatch('user/handleLogout');
                }
                break;

            case 401:
                // 不是获取权限菜单
                if (config.url !== '/api/menus/') {
                    window.$message && window.$message({type: 'error', message: '无权限，请联系管理员'});
                }
                break;

            default:
                break;
        }
        console.error('error :>> ', error);

        return Promise.reject(error);
    }
);

export default service;
